package com.jnu.supermarket;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jnu.supermarket.data.DataBank;
import com.jnu.supermarket.data.ShopItem;

import java.util.List;

public class ShopItemFragment extends Fragment {

    public static final int RESULT_CODE_ADD_DATA = 996;
    private List<ShopItem> shopItems;
    private ShopItemFragment.MyRecyclerViewAdapter recyclerviewAdapter;
    private DataBank dataBank;

    ActivityResultLauncher<Intent> launcherAdd = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA){
                if(null==data)return;
                String name=data.getStringExtra("name");
                double price=data.getDoubleExtra("price",0);
                int position=data.getIntExtra("position",shopItems.size());
                shopItems.add(position,new ShopItem(name,R.drawable.book_no_name,price));
                dataBank.saveData();
                recyclerviewAdapter.notifyItemInserted(position);
            }
        }
    });
    ActivityResultLauncher<Intent>  launcherEdit = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA) {
                if(null==data)return;
                String name = data.getStringExtra("name");
                double price = data.getDoubleExtra("price", 0);
                int position = data.getIntExtra("position", shopItems.size());
                shopItems.get(position).setName(name);
                shopItems.get(position).setPrice(price);
                dataBank.saveData();
                recyclerviewAdapter.notifyItemChanged(position);
            }
        }
    });

    public ShopItemFragment() {
        // Required empty public constructor
    }

    public static ShopItemFragment newInstance() {
        ShopItemFragment fragment = new ShopItemFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View rootView=inflater.inflate(R.layout.fragment_shop_item, container, false);
        initData();//初始化商品数据

        //添加FloatingActionButton
        FloatingActionButton fabAdd=rootView.findViewById(R.id.floating_action_button_add);
        fabAdd.setOnClickListener(view -> {
                Intent intent=new Intent(ShopItemFragment.this.getContext(),InputActivity.class);
                intent.putExtra("position",shopItems.size());
                launcherAdd.launch(intent);
        });

        RecyclerView mainRecyclerView = rootView.findViewById(R.id.recycler_view_items);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext());
        mainRecyclerView.setLayoutManager(layoutManager);

        recyclerviewAdapter = new ShopItemFragment.MyRecyclerViewAdapter(shopItems);
        mainRecyclerView.setAdapter(recyclerviewAdapter);//设置变压器作用：将数据转化为视图，而View只负责显示，不负责创建
        //创建调节器的时候就将商品列表的数据传给调节器
        return rootView;
    }

    public void initData(){
        dataBank = new DataBank(this.getContext());
        shopItems= dataBank.loadData();
    }

    private class MyRecyclerViewAdapter extends RecyclerView.Adapter<ShopItemFragment.MyRecyclerViewAdapter.MyViewHolder>  {
        private List<ShopItem> shopItems;

        public MyRecyclerViewAdapter(List<ShopItem> shopItems) {
            this.shopItems=shopItems;
        }

        @NonNull
        @Override
        public ShopItemFragment.MyRecyclerViewAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.shop_item_holder, parent, false);

            return new ShopItemFragment.MyRecyclerViewAdapter.MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ShopItemFragment.MyRecyclerViewAdapter.MyViewHolder holder, int position) {
            holder.getImageView().setImageResource(shopItems.get(position).getPictureId());
            holder.getTextViewName().setText(shopItems.get(position).getName());
            holder.getTextViewPrice().setText(String.valueOf(shopItems.get(position).getPrice()));
        }

        @Override
        public int getItemCount() {
            return shopItems.size();
        }

        private class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
            public static final int CONTEXT_MENU_ID_ADD = 1;
            public static final int CONTEXT_MENU_ID_EDIT = CONTEXT_MENU_ID_ADD+1;
            public static final int CONTEXT_MENU_ID_DELETE = CONTEXT_MENU_ID_ADD+2;

            private final ImageView imageView;
            private final TextView textViewName;
            private final TextView textViewPrice;

            public MyViewHolder(View itemview) {
                super(itemview);

                this.imageView=itemview.findViewById(R.id.image_view_shop_item);
                this.textViewName=itemview.findViewById(R.id.text_view_shop_item_name);
                this.textViewPrice=itemview.findViewById(R.id.text_view_shop_item_price);

                itemview.setOnCreateContextMenuListener(this);//让这一行中任何一个地方都会弹出这个菜单（一张图两个文本）
                //让这一行去创建菜单，让他去设置一个OnContextClickListener
            }
            public ImageView getImageView() {
                return imageView;
            }
            public TextView getTextViewName() {
                return textViewName;
            }
            public TextView getTextViewPrice() {
                return textViewPrice;
            }
            @Override
            public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                int position=getAdapterPosition();
                MenuItem menuItemAdd=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_ADD,CONTEXT_MENU_ID_ADD,getString(R.string.string_add));
                MenuItem menuItemEdit=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_EDIT,CONTEXT_MENU_ID_EDIT,getString(R.string.string_edit));
                MenuItem menuItemDelete=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_DELETE,CONTEXT_MENU_ID_DELETE,getString(R.string.string_delete));

                menuItemAdd.setOnMenuItemClickListener(this);
                menuItemEdit.setOnMenuItemClickListener(this);
                menuItemDelete.setOnMenuItemClickListener(this);
            }

            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                int position=getAdapterPosition();
                Intent intent;
                switch(menuItem.getItemId())
                {
                    case CONTEXT_MENU_ID_ADD:
                        intent = new Intent(ShopItemFragment.this.getContext(),InputActivity.class);
                        intent.putExtra("position",position);
                        launcherAdd.launch(intent);
                        break;
                    case CONTEXT_MENU_ID_EDIT:
                        intent = new Intent(ShopItemFragment.this.getContext(),InputActivity.class);
                        intent.putExtra("position",position);
                        intent.putExtra("name",shopItems.get(position).getName());//传名称编辑
                        intent.putExtra("price",shopItems.get(position).getPrice());//传价格编辑
                        launcherEdit.launch(intent);
                        break;
                    case CONTEXT_MENU_ID_DELETE://修改delete功能
                        AlertDialog.Builder alertDB = new AlertDialog.Builder(ShopItemFragment.this.getContext());
                        //确定
                        alertDB.setPositiveButton(ShopItemFragment.this.getContext().getResources().getString(R.string.string_confirmation), (dialogInterface, i) -> {
                            shopItems.remove(position);
                            dataBank.saveData();
                            ShopItemFragment.MyRecyclerViewAdapter.this.notifyItemRemoved(position);
                        });
                        //取消
                        alertDB.setNegativeButton(ShopItemFragment.this.getContext().getResources().getString(R.string.string_cancel), (dialogInterface, i) -> {

                        });
                        //对话框内容：确定要删除。。。吗？
                        alertDB.setMessage(ShopItemFragment.this.getContext().getResources().getString(R.string.string_confirm_delete) +shopItems.get(position).getName()+"？");
                        //对话框标题：提示
                        alertDB.setTitle(ShopItemFragment.this.getContext().getResources().getString(R.string.hint)).show();
                        break;
                }

                Toast.makeText(ShopItemFragment.this.getContext(),"点击了"+menuItem.getTitle(),Toast.LENGTH_LONG).show();
                return false;
            }
        }
    }
}